//
//  NDWebView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/11/1.
//

import SwiftUI
import WebKit

struct NDWebView: View {
    let urlString: String?
    let isFollowOrder: Bool
    let isPresent: Bool
    @Environment(\.presentationMode) var presentationMode
    @StateObject private var viewModel = NDWebViewModel()
    @Environment(\.navigationManager) var navManager
    
    var body: some View {
        let navigationConfig = NavigationConfig(
            title: viewModel.title,
            showSystemBackButton: false
        )
        
        NDBaseContentView(navigationConfig: navigationConfig) {
            ZStack(alignment: .top) {
                // WebView
                NDWebRepresentable(
                    urlString: urlString,
                    viewModel: viewModel,
                    navManager: navManager
                )
                .edgesIgnoringSafeArea(.all)
                
                // 进度条
                if viewModel.showProgress {
                    ProgressView(value: viewModel.progress)
                        .progressViewStyle(LinearProgressViewStyle(tint: Color(hex: "#FF9068")))
                        .frame(height: 2)
                        .padding(.top, 1)
                }
            }
        }
        .navigationBarBackButtonHidden(true)
        .navigationBarItems(leading: backButton)
        .onAppear {
            viewModel.loadWebContent(urlString: urlString)
        }
        .onReceive(viewModel.$shouldClose) { shouldClose in
            if shouldClose {
                closeWebView()
            }
        }
        .onReceive(viewModel.$shouldGoHome) { shouldGoHome in
            if shouldGoHome {
                goToHome()
            }
        }
    }
    
    private var backButton: some View {
        Button(action: handleBackAction) {
            Image(systemName: "chevron.left")
                .renderingMode(.template)
                .foregroundColor(.black)
        }
    }
    
    private func handleBackAction() {
        if viewModel.canGoBack {
            viewModel.goBack()
        } else {
            closeWebView()
        }
    }
    
    private func closeWebView() {
        if isPresent {
            presentationMode.wrappedValue.dismiss()
        } else {
            if isFollowOrder {
                // 跳转到根视图
                navManager.wrappedValue.popToRoot(tag: mainNav, animated: true)
            } else {
                presentationMode.wrappedValue.dismiss()
            }
        }
    }
    
    private func goToHome() {
        presentationMode.wrappedValue.dismiss()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            NotificationCenter.default.post(
                name: .schemeSwitchTab,
                object: nil,
                userInfo: [NDSchemeKeys.tabIndex: 0]
            )
            NotificationCenter.default.post(name: .schemeRefreshHome, object: nil)
        }
    }
}

